#include "BallGame.h"

namespace TUMAR { namespace Snowman {
	BallGame::BallGame(void) : timer(this), finished(true), interval(30)
	{
	}

	BallGame::~BallGame(void)
	{
		this->timer.Stop();
	}

	void BallGame::Start(cv::Vec3d start, cv::Vec3d target)
	{
		this->timer.Stop();
		this->finished = false;

		this->angle = 3.14159265 / 4;
		this->velocity = sqrt((length(subtract(target, start)) / sin(2 * this->angle)) * 9.81);
		this->position = cv::Vec3d(0, 0, 0);
		this->time = 0;

		this->timer.Schedule(this->interval);
	}

	bool BallGame::IsFinished(void)
	{
		return this->finished;
	}

	void BallGame::Update(void)
	{
		this->time += this->interval / 1000.0;

		this->position[0] = 0;
		this->position[1] = this->velocity * cos(this->angle) * this->time;
		this->position[2] = (-9.81 / 2) * (this->time * this->time) + this->velocity * sin(this->angle) * this->time;

		if(this->position[2] < 0)
		{
			this->timer.Stop();
			this->finished = true;
		}
	}

	const cv::Vec3d* BallGame::GetCurrentBallPosition(void)
	{
		return &this->position;
	}

	
	BallGameTimer::BallGameTimer(BallGame* game) : game(game)
	{
	}

	void BallGameTimer::Tick(void) const
	{
		this->game->Update();
	}
}}
